<template>
  <div class="card" ref="topRef">
    <a-spin :spinning="loading">
      <div style="margin-bottom: 20px">
        <a-button type="primary" icon="left" @click="back()"> 返回 </a-button>
        <span class="titleStyle">计划详情</span>
      </div>
      <a-descriptions bordered>
        <a-descriptions-item label="用户姓名">{{ planInfo.realname }}</a-descriptions-item>
        <a-descriptions-item label="信用卡名称"> {{ planInfo.bank_name }}</a-descriptions-item>
        <a-descriptions-item label="通道名称">{{ planInfo.channel_name }} </a-descriptions-item>
        <a-descriptions-item label="用户手机号">{{ planInfo.phone }} </a-descriptions-item>
        <a-descriptions-item label="信用卡卡号">{{ planInfo.bank_num }}</a-descriptions-item>
        <a-descriptions-item label="计划周期">
          {{ planInfo.plan_start_date }} ~ {{ planInfo.plan_end_date }}
        </a-descriptions-item>
        <a-descriptions-item label="用户身份证">{{ planInfo.id_card }}</a-descriptions-item>
        <a-descriptions-item label="提交时间">{{ planInfo.ctime }}</a-descriptions-item>
        <a-descriptions-item label="实际结束时间">{{ planInfo.plan_finish_date }}</a-descriptions-item>
        <a-descriptions-item label="落地城市">{{ planInfo.city_name }}</a-descriptions-item>
        <a-descriptions-item label="计划还款金额">
          {{ planInfo.amount }}，生成{{ planInfo.repay_amount }}
        </a-descriptions-item>
        <a-descriptions-item label="未还款金额">{{ planInfo.waiting_repayment_amount }}</a-descriptions-item>
        <a-descriptions-item label="卡内预留额度">{{ planInfo.max_group_pay_amount }}</a-descriptions-item>
        <a-descriptions-item label="消费手续费">
          {{ planInfo.pay_fee }}，已扣{{ planInfo.subtracted_service_fee }}
        </a-descriptions-item>
        <a-descriptions-item label="已消费金额">{{ planInfo.has_pay_amount }}</a-descriptions-item>
        <a-descriptions-item label="处理结果">
          <div>{{ planInfo.info }}</div>
        </a-descriptions-item>
        <a-descriptions-item label="还款笔数费">
          {{ planInfo.repay_fee }}，已扣{{ planInfo.subtracted_num_fee }}
        </a-descriptions-item>
        <a-descriptions-item label="已还款金额"> {{ planInfo.subtracted_num_fee }}</a-descriptions-item>
        <a-descriptions-item label="计划状态">{{ planInfo.status_text }}</a-descriptions-item>
        <a-descriptions-item label="模式">{{ modeFilter(planInfo.mode) }}</a-descriptions-item>
        <a-descriptions-item label="账单日/还款日">
          {{ planInfo.bill_day }}/ {{ planInfo.repayment_day }}
        </a-descriptions-item>
        <a-descriptions-item label="子商户号">
          <span> {{ channel_mer_no || '暂无' }} </span>
        </a-descriptions-item>
        <a-descriptions-item label="结算卡">
          <span class="linkStyle" @click="viewCard(no)">{{ no || '暂无结算卡' }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="审核状态">
          {{ state || '暂无' }}
        </a-descriptions-item>

        <a-descriptions-item label="余额">
          <a-spin :spinning="moneyLoading">
            <span class="linkStyle" disabled> {{ queryMoney }} </span>
          </a-spin>
        </a-descriptions-item>
        <!-- <a-descriptions-item> </a-descriptions-item>
        <a-descriptions-item> </a-descriptions-item> -->
      </a-descriptions>
      <div class="titleStyle" style="margin: 20px 0">子计划详情</div>
      <div v-for="(item, index) in planInfo.plans" :key="item.id">
        <div :ref="`date${index}`">{{ index }}</div>
        <p style="margin: 20px 0">
          已消费金额: {{ item.stat.pay_amount }}已还款金额: {{ item.stat.repay_amount }}消费手续费:
          {{ item.stat.pay_fee }}还款手续费: {{ item.stat.repay_fee }} 消还组数:
          {{ item.stat.exec_group_count }} 未执行还款: {{ item.stat.wait_repay_money }}
        </p>
        <div>
          <a-button class="btnStyle" type="primary" size="small" @click="AddSubplanList(index)">添加</a-button>
          <a-button class="btnStyle" type="danger" size="small" disabled>删除</a-button>
          <a-button class="btnStyle" type="danger" size="small" @click="editRef()" disabled>修改</a-button>
          <a-button class="btnStyle" type="danger" size="small" disabled>显示/隐藏</a-button>
        </div>
        <a-table
          :rowKey="(record, index) => index"
          style="margin: 20px 0; border: 1px solid #e8e8e8"
          :columns="columns"
          :data-source="item.list"
          :pagination="false"
        >
          <template slot="check">
            <a-checkbox disabled v-model="item.allCheck" @change="allChange"></a-checkbox>
          </template>
          <div slot="checkbox" slot-scope="text, record">
            <span><a-checkbox disabled v-model="record.checkValue" @change="onChange(record.id)"></a-checkbox></span>
          </div>
          <div slot="status" slot-scope="text, record">
            <span :style="`color:${statusColor(record.status)}`">{{ statusType(record.status) }}</span>
          </div>
          <div slot="type" slot-scope="text, record">
            <span>{{ record.trade_type_txt }}</span>
          </div>
          <div slot="trade_info" slot-scope="text, record">
            <span class="branchStyle">{{ record.trade_info }}</span>
          </div>
          <div slot="operat" slot-scope="text, record">
            <span class="linkStyle" @click="execute(record.id)">执行</span>
            <span class="lineStyle" style="margin: 0">丨</span>
            <span class="linkStyle" @click="refund(record.id)">退款</span>
            <span class="lineStyle" style="margin: 0">丨</span>
            <span
              class="linkStyle"
              @click="
                edit(record.id, record.trade_date, record.status, record.trade_time, record.trade_amount, record.utime)
              "
            >
              修改
            </span>
            <span class="lineStyle" style="margin: 0">丨</span>
            <span class="linkStyle" @click="del(record.id)">删除</span>
            <span class="lineStyle" style="margin: 0">丨</span>
            <span
              class="linkStyle"
              @click="remark(record.remark, record.id)"
              :style="`color: ${record.remark ? '#ff0000' : '#1890ff'}`"
            >
              备注
            </span>
          </div>
        </a-table>
      </div>
    </a-spin>
    <EditContent
      :isShowPlan.sync="isShowPlan"
      :date.sync="date"
      :status.sync="status"
      :trade_time.sync="trade_time"
      :trade_amount.sync="trade_amount"
      :id.sync="id"
      :utime.sync="utime"
      @upload="getInfo"
    />
    <a-modal
      v-model="isShowRemark"
      wdith="40%"
      title="备注"
      ok-text="确认"
      cancel-text="取消"
      @cancel="hideModal"
      @ok="handleOk"
    >
      <a-textarea v-model="remarkValue" placeholder="请输入备注信息" :rows="4" />
    </a-modal>
    <a-modal
      v-model="isShowResult"
      wdith="60%"
      ok-text="确认"
      cancel-text="取消"
      @cancel="closeResult"
      @ok="closeResult"
      title="返回结果"
    >
      <a-textarea v-model="resultContent" :rows="12" />
    </a-modal>
    <div class="backTopStyle">
      <a-button icon="arrow-down" @click="editRef()" type="primary">跳转今日</a-button>
      <a-button icon="arrow-up" @click="backTop()" type="primary">返回顶部</a-button>
    </div>
    <AddSubplan :isShowAddSubplan.sync="isShowAddSubplan" :addDate.sync="addDate" @upload="getInfo" />
  </div>
</template>

<script>
import { format } from 'date-fns'
import AddSubplan from './dialog/AddSubplan'
import EditContent from './dialog/EditContent.vue'
import { getPlanInfoAPI, editRemarkAPI, delInfoAPI, executeAPI, refundAPI, getMoneyAPI } from '@/api/transaction.js'
export default {
  name: 'PlanDetails',
  components: {
    EditContent,
    AddSubplan
  },
  data() {
    return {
      channel_mer_no: '',
      state: '',
      no: '',
      moneyLoading: false,
      queryMoney: '',
      resultContent: '',
      isShowResult: false,
      utime: '',
      addDate: '',
      isShowAddSubplan: false,
      id: undefined,
      remarkValue: '',
      isShowRemark: false,
      trade_amount: '',
      trade_time: '',
      status: '',
      date: '',
      isShowPlan: false,
      cidType: [
        { id: '0', name: '未执行', color: '#ff8c11' },
        { id: '1', name: '排队中', color: '#00d98f' },
        { id: '2', name: '执行中', color: '#00d98f' },
        { id: '-20', name: '已补单', color: '#fccb21' },
        { id: '-30', name: '失败', color: '#ff0000' },
        { id: '30', name: '成功', color: '#00be0d' },
        { id: '-10', name: '取消', color: '#666666' }
      ],
      columns: [
        {
          align: 'center',
          scopedSlots: { customRender: 'checkbox', title: 'check' }
        },
        {
          title: '代还编号',
          dataIndex: 'id',
          align: 'center'
        },
        {
          title: '通道',
          dataIndex: 'channel_code',
          align: 'center'
        },
        {
          title: '交易时间',
          dataIndex: 'trade_time',
          align: 'center'
        },
        {
          title: '交易金额',
          dataIndex: 'trade_amount',
          align: 'center'
        },
        {
          title: '交易手续费',
          dataIndex: 'trade_service_fee',
          align: 'center'
        },
        {
          title: '订单号',
          dataIndex: 'order_sn',
          align: 'center'
        },
        {
          title: '交易状态',
          dataIndex: 'status',
          align: 'center',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '交易类型',
          align: 'center',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '交易信息',
          dataIndex: 'trade_info',
          width: '150px',
          scopedSlots: { customRender: 'trade_info' },
          align: 'center'
        },
        {
          title: '操作',
          align: 'center',
          scopedSlots: { customRender: 'operat' }
        }
      ],
      loading: false,
      modeType: [
        { id: 'novice', name: '新手', color: 'green' },
        { id: 'custom', name: '自定义', color: 'blue' },
        { id: 'empty', name: '空卡', color: 'purple' },
        { id: 'urgent', name: '应急', color: 'red' }
      ],
      planInfo: {}
    }
  },
  created() {
    this.getInfo()
  },
  methods: {
    editRef() {
      console.log(this.$refs[`date${format(new Date(), 'yyyy-MM-dd')}`][0].offsetTop)
      this.$refs.topRef.scrollTo({
        top: this.$refs[`date${format(new Date(), 'yyyy-MM-dd')}`][0].offsetTop,
        behavior: 'smooth'
      })
      console.log(this.$refs[`date${format(new Date(), 'yyyy-MM-dd')}`][0].offsetTop)
    },
    backTop() {
      console.log(this.$refs.topRef.scrollTo)
      this.$refs.topRef.scrollTo({ top: 0, behavior: 'smooth' })
    },
    viewCard(id) {
      if (!id) return
      this.$router.push({ path: '/userinfo/account', query: { card: id } })
      console.log(id)
    },
    async refund(id) {
      this.$confirm({
        title: '确定要退款吗？',
        content: h => <div style="color:red">此操作不可撤回</div>,
        onOk: async () => {
          try {
            const result = await refundAPI({ id })
            this.resultContent = JSON.stringify(result)
            this.isShowResult = true
            this.$message.success('操作成功')
            this.getInfo()
          } catch (error) {
            this.resultContent = JSON.stringify(error.data)
            this.isShowResult = true
            this.getInfo()
          }
        },
        onCancel: () => {
          return
        },
        class: 'test'
      })
    },
    closeResult() {
      this.isShowResult = false
    },
    execute(id) {
      this.$confirm({
        title: '确定要执行吗？',
        content: h => <div style="color:red">此操作不可撤回</div>,
        onOk: async () => {
          try {
            const result = await executeAPI({ id })
            this.resultContent = JSON.stringify(result)
            this.isShowResult = true
            this.$message.success('操作成功')
            this.getInfo()
          } catch (error) {
            this.resultContent = JSON.stringify(error.data)
            this.isShowResult = true
            this.getInfo()
          }
        },
        onCancel: () => {
          return
        },
        class: 'test'
      })
    },
    AddSubplanList(date) {
      this.addDate = date
      this.isShowAddSubplan = true
    },
    back() {
      this.$router.back()
    },
    onChange() {
      console.log(1)
    },
    allChange() {
      console.log(this.planInfo.plans)
    },
    async getInfo() {
      try {
        this.moneyLoading = true
        this.loading = true
        const { data } = await getPlanInfoAPI({ brand_id: process.env.VUE_APP_BRAND_ID, id: this.$route.query.id })
        Object.values(data.plans).map(item => {
          item.allCheck = false
          item.list.map(value => {
            value.checkValue = false
            return value
          })
          return item
        })
        this.planInfo = data
        this.no = this.planInfo?.debit_card?.no || ''
        this.state = this.planInfo?.debit_card?.state_text || ''
        this.channel_mer_no = this.planInfo?.debit_card?.channel_mer_no || ''
        try {
          const getMoney = await getMoneyAPI({ id: this.planInfo.id })
          this.queryMoney = getMoney.data.amount
        } finally {
          this.moneyLoading = false
        }
      } finally {
        this.loading = false
      }
    },
    modeFilter(params) {
      return this.modeType.find(item => item.id == params)?.name || ''
    },
    statusType(value) {
      return this.cidType.find(item => item.id == value)?.name || ''
    },
    statusColor(value) {
      return this.cidType.find(item => item.id == value)?.color || ''
    },
    edit(id, date, status, trade_time, trade_amount, utime) {
      this.utime = utime
      this.id = id
      this.utime = utime
      this.trade_amount = trade_amount
      this.trade_time = trade_time
      this.status = status
      this.date = date
      this.isShowPlan = true
    },
    remark(content, id) {
      this.id = id
      this.remarkValue = content
      this.isShowRemark = true
    },
    hideModal() {
      this.isShowRemark = false
      this.id = ''
      this.remarkValue = ''
    },
    async handleOk() {
      try {
        await editRemarkAPI({
          brand_id: process.env.VUE_APP_BRAND_ID,
          ids: this.id,
          remark: this.remarkValue
        })
        this.getInfo()
        this.isShowRemark = false
        this.id = ''
        this.remarkValue = ''
        this.$message.success('操作成功')
      } catch (error) {
        this.$message.error(error.data.msg)
      }
    },
    async del(id) {
      this.$confirm({
        title: '确定要删除吗？',
        content: h => <div style="color:red">此操作不可撤回</div>,
        onOk: async () => {
          try {
            await delInfoAPI({ brand_id: process.env.VUE_APP_BRAND_ID, ids: id })
            this.$message.success('操作成功')
            this.getInfo()
          } catch (error) {
            this.$message.error(error.data.msg)
          }
        },
        onCancel: () => {
          return
        },
        class: 'test'
      })
    }
  }
}
</script>

<style lang="less" scoped>
/* CSS样式 */
.card::-webkit-scrollbar {
  width: 8px; /* 设置滚动条宽度 */
}

.card::-webkit-scrollbar-thumb {
  background-color: #999; /* 设置滑块颜色 */
}

.card::-webkit-scrollbar-track {
  background-color: #f5f5f5; /* 设置滚动条背景颜色 */
}
.card {
  height: 85vh;
  overflow-y: scroll;
}
.btnStyle {
  margin-right: 10px;
}
.titleStyle {
  margin-left: 20px;
  font-size: 16px;
  font-weight: 700;
  color: #262626;
}
.backTopStyle {
  position: absolute;
  right: 30px;
  bottom: 30px;
}

.branchStyle {
  white-space: normal;
}
</style>
